import { Router } from "vue-router";
import { useAppStore } from "@scpun/stores";
import { startProgress, stopProgress, useTitle } from "@scpun/core";

const setupCommonGuard = (router: Router) => {
    // 记录已经加载的页面
    const loadedPaths = new Set<string>();
    const appStore = useAppStore();
    const appName = import.meta.env.VITE_APP_TITLE;

    router.beforeEach((to) => {
        to.meta.loaded = loadedPaths.has(to.path);

        // 页面加载进度条
        if (!to.meta.loaded && appStore.showProgress) {
            startProgress();
        }
        return true;
    });

    router.afterEach((to) => {
        // 记录页面是否加载,如果已经加载，后续的页面切换动画等效果不在重复执行

        loadedPaths.add(to.path);

        // 关闭页面加载进度条
        if (appStore.showProgress) {
            stopProgress();
        }

        // 动态修改标题
        const { title } = to.meta;
        useTitle(`${title} - ${appName}`);
    });
};

export { setupCommonGuard };
